package com.sgu6.sgu6_machine.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.base.BaseA;
import com.sgu6.sgu6_machine.util.NetUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NetStableCheckA extends BaseA {


    private static final String TAG = NetStableCheckA.class.getSimpleName();
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.btn_start)
    Button btnStart;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_result)
    TextView tvResult;

    private int pingNo = 30;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_stable);
        ButterKnife.bind(this);
        initUI();
    }

    @Override
    public void initUI() {
        initToolbar();
    }


    private void initToolbar() {
        toolbar.setTitle("网络状态检测");
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setBackgroundResource(R.color.colorPrimaryDark);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return true;
    }

    @OnClick(R.id.btn_start)
    public void onViewClicked() {
        tvStatus.setText("检测状态：检测中");

        if (NetUtil.getNetWorkState(this)==-1){
            tvResult.setText("检测结果：网络未连接");
        }else{
            tvResult.setText("检测结果：");
            ThreadManager.getThreadPollProxy().execute(new Runnable() {
                @Override
                public void run() {
                    List<String> results = execPingCmd(pingNo, "www.sgu6.com");
                    if (results.get(0).equals("0")) {
                        String result = analyseResult(pingNo, results);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvStatus.setText("检测状态：检测完成");
                                tvResult.setText(String.format("检测结果：%s", result));
                            }
                        });
                    }
                }
            });
        }
    }

    /**
     * ping 命令
     *
     * @param pingNum            测试次数
     * @param m_strForNetAddress ip 10.83.50.111
     *                           5 packets transmitted, 5 received, 0% packet loss, time 2405ms
     *                           发出去的包数，返回的包数，丢包率，耗费时间
     *                           rtt min/avg/max/mdev
     *                           最小/平均响应时间/最大/本机硬件耗费时间
     * @return
     */
    private List<String> execPingCmd(int pingNum, String m_strForNetAddress) {
        List<String> result = new ArrayList<>();
        StringBuffer tv_PingInfo = new StringBuffer();
        try {
            Process p = Runtime.getRuntime().exec("ping -c " + pingNum + " " + m_strForNetAddress);
            int status = p.waitFor();
            if (status == 0) {
                result.add("0");
            } else {
                result.add("1");
            }
            BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String str;
            // 读出全部信息并显示
            while ((str = buf.readLine()) != null) {
                result.add(str);
            }
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    private String analyseResult(int pingNum, List<String> results) {
        int length = results.size();
        if (length > 2) {
            String resultWithSpace = results.get(length - 2).replace(" ", "");
            String[] rs = resultWithSpace.split(",");
            int percent_index = rs[2].indexOf("%");
            String str = rs[2].substring(0, percent_index);
            int percent = Integer.parseInt(str);
            if (percent == 0) {
                return "网络稳定";
            } else if (percent == 1) {
                return "网络较稳定";
            } else {
                return "网络不稳定";
            }
        } else {
            return "网络未连接";
        }

    }
}
